package g7.converter;

import g7.facade.SprintFacade;
import g7.modelo.Sprint;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;


@FacesConverter(value="sprint", forClass = Sprint.class)
public class SprintConverter implements Converter {
	
	public static SprintFacade sprintFacade;
	
	static{
		sprintFacade = new SprintFacade();
	}
	
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		
//		FacesContext context = FacesContext.getCurrentInstance();
//		MotivoQuestaoMotivo motivo = context.getApplication().evaluateExpressionGet(context, "#{motivo}", MotivoQuestaoMotivo.class);
		
		String sprintDescricao;
			
		try {
			if(arg2!=null && !arg2.isEmpty()){
				sprintDescricao = arg2;
				
				Sprint sprint = sprintFacade.procurarPorObjetivo(sprintDescricao);
//				System.out.println("Motivo "+motivo.getFormulario().getTitulo()+" Contains = "+motivo.getMotivo().getOpcoes().contains(sprint));
				
//					if(motivo.getMotivo().getOpcoes().contains(sprint))
						return sprint;
//					else
//						return null;
			}
		} catch (NumberFormatException exception) {
			throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Type the name of a Sprint and select it (or use the dropdow)", "Type the name of a Sprint and select it (or use the dropdow)"));
		}

		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {

//		FacesContext context = FacesContext.getCurrentInstance();
//		MotivoQuestaoMotivo motivo = context.getApplication().evaluateExpressionGet(context, "#{motivo}", MotivoQuestaoMotivo.class);
		
		if (arg2 == null || (arg2 instanceof String)) {
			return "";
		}
		
		Sprint sprint = (Sprint) arg2;
//		System.out.println("Motivo "+motivo.getFormulario().getTitulo()+" Contains = "+motivo.getMotivo().getOpcoes().contains(sprint));
		
//		if(motivo.getMotivo().getOpcoes().contains(sprint))
			return String.valueOf(sprint.getObjetivo());
//		else
//			return "";
	}
	
}
